//
//  YQOrderRefundVC.m
//  MuYing
//
//  Created by tbb on 2019/8/26.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "YQOrderRefundVC.h"
#import "YJPublishSelectImageCell.h"
#import "PostImageCell.h"
#import "YQImagePickerBaseVC.h"
#import "YQOrderDetailsBottonView.h"
#import "YQBottonAlertView.h"
#import "YQGoodsOrderModel.h"
#import "YQGoodsOrderDetailsModel.h"
#import "YQOrderLogisticsWriteVC.h"
#define KYJPublishSelectImageSize ((kYQPScreenWidth-24-20) / 3.0)
@interface YQOrderRefundVC ()<YJPublishSelectImageCellDelegate>
@property (nonatomic, strong) UIImage * addImg;
@property (nonatomic, strong) NSMutableArray * imageArr;
@property (nonatomic, strong)  NSMutableArray * imageUrlArr;
@property (nonatomic, strong) YQOrderDetailsBottonView * bottonView;

@property (nonatomic, copy) NSString * reason;
@property (nonatomic, copy) NSArray * reasonArr;

@property (nonatomic, copy) NSString * goodsState;
@property (nonatomic, strong) YQGoodsOrderDetailsModel * orderDetailsModel;

@property (nonatomic, assign) NSInteger refundType;


@end

@implementation YQOrderRefundVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isNavShadow = YES;
    self.reasonArr = @[kYQLS(@"卖家发错货"),kYQLS(@"少件/漏发"),kYQLS(@"包装/商品破损"),kYQLS(@"质量问题"),kYQLS(@"大小/重量与商品描述不符")];
    if (self.type == 0) {
        self.navigationItem.title = kYQLS(@"仅退款");
    }else{
        self.navigationItem.title = kYQLS(@"退货退款");
    }
}

-(void)setupView {
    [super setupView];
    self.addImg = YQIMG(@"yj_add_pic_iocn");
    [self.imageArr addObject:self.addImg];
    self.listTableView.backgroundColor = kAPPTABLEVIEW_BG_COLOR;
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea-49);
    [self.view addSubview:self.bottonView];
    [self.bottonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-kHeight_Botton_SafeArea);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManageGoodsCell");
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderRefundPriceCell");
    kYQREGISTERTABLEVIEWNIBCELL(@"MYMySetTextCell");
    kYQREGISTERTABLEVIEWCELL([YJPublishSelectImageCell class]);
//    self.listTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self getDetailsData];
//    }];
//    [self getDetailsData];
}

-(void)getDetailsData{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"orderId"] = self.OrderModel.orderItemId;
    parameters[@"orderType"] = @(self.detailModel.orderType);
    
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:kPOST_GOODS_ORDER_INFO_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        [self stopRefresh];
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            self.orderDetailsModel = [YQGoodsOrderDetailsModel modelWithJSON:responseObject.data];
            [self.listTableView reloadData];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
//        YQUITIPSERROR(error)
        [self stopRefresh];
    }];
    
}
-(void)refundAction:(UIButton *)sender {
    if (!self.reason) {
        kMBMesHUD(kYQLS(@"请选择退款理由"));
        return;
    }
    if(!self.goodsState) {
        kMBMesHUD(kYQLS(@"请选择货物状态"));
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"amount"] = @(self.OrderModel.payAmount);
    parameters[@"comment"] = self.OrderModel.connent;
    parameters[@"orderId"] = self.OrderModel.orderItemId;
    parameters[@"orderType"] = @(self.detailModel.orderType);
    parameters[@"pictures"] = [self.imageUrlArr componentsJoinedByString:@","];
    parameters[@"reason"] = self.reason;
    NSString *typeStr = @"";
    if (self.type == 0) {
        //1 仅退款
        typeStr = @"1";
    }else{
        //2用户退货退款
        typeStr = @"2";
    }
//    if (self.type == 0 && self.refundType == 0) {
//        //0 未收货仅退款
//        typeStr = @"0";
//    }else if (self.type == 0 && self.refundType == 1) {
//        //1 已收货（无需退货）
//        typeStr = @"1";
//    }else{
//        //2用户退货退款
//        typeStr = @"2";
//    }
    parameters[@"type"] = typeStr;
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:kPOST_REFUND_SUBMIT_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            YQUITIPSSUCCEED(responseObject.msg)
            if (self.ssucceeBlock) {
                self.ssucceeBlock();
            }
            [self.navigationController popViewControllerAnimated:true];
//            if (self.type == 0) {
//                [self.navigationController popViewControllerAnimated:true];
//            }else{
//                YQOrderLogisticsWriteVC *writeVC = [YQOrderLogisticsWriteVC new];
//                kYQPUSH(writeVC);
//            }
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
        YQHIDELOADINGTIPS
    }];
    
    
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return 3;
    }else if (section == 2) {
        return 2;
    }
    return self.orderDetailsModel.orderItemList.count;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == 0) {        
        YQOrderManageGoodsCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManageGoodsCell"];
        goodsCell.goodsModel = self.OrderModel;
        return goodsCell;
    }else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            YQOrderRefundPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderRefundPriceCell"];
            cell.titleLb.text = kYQLS(@"预计退款金额");
            
            cell.priceTextField.placeholder = [NSString stringWithFormat:@"%.2lf", self.OrderModel.payAmount ];//(%@%.2lf),kYQLS(@"含运费"),[self.orderDetailsModel.freightAmount doubleValue]
            cell.priceTextField.userInteractionEnabled = NO;
            /*
            if (self.type == 0) {
                cell.priceTextField.userInteractionEnabled = NO;
            }else{
                cell.priceTextField.userInteractionEnabled = YES;
            }
             */
            return cell;
        }else{
            MYMySetTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYMySetTextCell"];
            cell.subLb.text = kYQLS(@"请选择");
            if (indexPath.row == 1) {
                cell.titleLb.text = kYQLS(@"退款理由");
                if (self.reason) {
                    cell.subLb.textColor = kAPPMainTitleColor;
                    cell.subLb.text = self.reason;
                }
            } else {
                if (self.goodsState) {
                    cell.subLb.textColor = kAPPMainTitleColor;
                    cell.subLb.text = self.goodsState;
                }
                cell.titleLb.text = kYQLS(@"货品状态");
            }
            
            
            return cell;
        }
    }else{
        if (indexPath.row == 0) {
            static NSString *cellStr = @"PostImageCell";
            PostImageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            if (!cell) {
                cell = [[PostImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
            }
            cell.addPostImageSourceBlock = ^{
                
            };
            cell.itemModel = self.orderDetailsModel.orderItemList.firstObject;
            return cell;
        }else{
            YJPublishSelectImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YJPublishSelectImageCell"];
            cell.delegate = self;
            cell.tempAddImag = self.addImg;
            cell.collImageArr = self.imageArr.copy;
            return cell;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 104;
    }else if (indexPath.section == 1) {
        return 58;
    }else {
        if (indexPath.row == 0) {
            return 87;
        }else{
            
            NSInteger row = 1;
            
            if (self.imageArr.count % 3 == 0) {
                row = self.imageArr.count / 3;
            } else {
                row = self.imageArr.count / 3 + 1;
            }
            
            return row * KYJPublishSelectImageSize + 10 * (row - 1)+12;
            
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ws(self);
    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            
            [YQBottonAlertView alertViewTitle:kYQLS(@"退货理由") dataSource:self.reasonArr defaultStr:self.reason ? self.reason : kYQLS(@"卖家发错货")  resultBlack:^(NSInteger row, id  _Nonnull result) {
                
                weakself.reason = result;
                [weakself.listTableView reloadData];
            }];
        }else if (indexPath.row == 2) {
            [YQBottonAlertView alertViewTitle:kYQLS(@"货物状态") dataSource:@[kYQLS(@"未收到货"),kYQLS(@"已收到货")] defaultStr:self.goodsState ? self.goodsState : kYQLS(@"未收到货")  resultBlack:^(NSInteger row, id  _Nonnull result) {
                weakself.goodsState = result;
                weakself.refundType = row;
                [weakself.listTableView reloadData];
            }];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 12;
    }
    return 0.001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end
#pragma mark -- lazy
-(NSMutableArray *)imageUrlArr {
    if (!_imageUrlArr) {
        _imageUrlArr = [NSMutableArray array];
    }
    return _imageUrlArr;
}
-(NSMutableArray *)imageArr {
    if (!_imageArr) {
        _imageArr = [NSMutableArray array];
    }
    return _imageArr;
}
-(YQOrderDetailsBottonView *)bottonView {
    if (!_bottonView) {
        _bottonView = [YQOrderDetailsBottonView viewFromXib];
        _bottonView.backgroundColor = UIColor.whiteColor;
        //2.设置阴影偏移范围
        _bottonView.layer.shadowOffset = CGSizeMake(0, 2);
        //3.设置阴影颜色的透明度
        _bottonView.layer.shadowOpacity = 0.5;
        
        //4.设置阴影半径
        _bottonView.layer.shadowRadius = 4;
        //5.设置阴影路径
        _bottonView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.navigationController.navigationBar.bounds].CGPath;
        [_bottonView.rightBtn setTitle:kYQLS(@"提交申请") forState:(UIControlStateNormal)];
        _bottonView.leftBtn.hidden = YES;
        [_bottonView.rightBtn addTarget:self action:@selector(refundAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _bottonView;
}
#pragma mark -- lazy end

#pragma mark -- YJPublishSelectImageCellDelegate

-(void)publishSelectionImageIndexPath:(NSIndexPath *)indexPath {
    YQImagePickerBaseVC *imagePickerVc = [[YQImagePickerBaseVC alloc] initWithMaxImagesCount:9 delegate:nil];
    imagePickerVc.maxImagesCount = 3 - self.imageArr.count + 1;
    
    ws(self);
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        if (photos.count <= 0) {
            return;
        }
        
        NSMutableArray *dataImageArr = @[].mutableCopy;
            
        for (UIImage *image in photos) {
            NSData *data = UIImageJPEGRepresentation(image, 0.8);
            [dataImageArr addObject:data];
        }
        
        
        YQSHOWLOADINGINVIEW
        [YQPNetWorkingManager sendPostRequests:kPOST_FILE_LIST_UPLOAD_URL parameters:nil fileDataArr:dataImageArr.copy fileName:@"files" success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            YQHIDELOADINGTIPS;
            if (responseObject.code == 0) {
                
                [self.imageUrlArr addObjectsFromArray:responseObject.data];
                
                [self.imageArr removeObject:weakself.addImg];
                [self.imageArr addObjectsFromArray:photos];
                if (self.imageArr.count < 6) {
                    [self.imageArr addObject:weakself.addImg];
                }else{
                    [self.imageArr removeObject:weakself.addImg];
                }
                
                [weakself.listTableView reloadData];
            }else{
                YQUITIPSERROR(responseObject.msg)
            }
        } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            YQHIDELOADINGTIPS;
            YQUITIPSERROR(error)
        }];

        
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}

-(void)deleteActionIndexPath:(NSIndexPath *)indexPath tableViewIndexPath:(NSIndexPath *)tableViewIndexPath {
    [self.imageArr removeObjectAtIndex:indexPath.item];
    
    if (self.addImg != self.imageArr.lastObject) {
        [self.imageArr addObject:self.addImg];
    }
    
    [self.imageUrlArr removeObjectAtIndex:indexPath.item];
    [self.listTableView reloadData];
}
#pragma mark -- YJPublishSelectImageCellDelegate end
@end
